package com.example.li_han.servlet;

import com.example.li_han.service.NewsTypeService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 删除分类Servlet（支持单个和批量删除）
 */
@WebServlet(name = "DeleteNewsType", value = "/DeleteNewsType")
public class DeleteNewsType extends HttpServlet {

    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        BufferedReader br = req.getReader();
        StringBuilder sbuffer = new StringBuilder();
        String s;

        while((s = br.readLine()) != null) {
            sbuffer.append(s);
        }

        String requestBody = sbuffer.toString();
        System.out.println("收到删除分类请求: " + requestBody);

        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 解析JSON数据
            Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
            Map<String, Object> rawData = gson.fromJson(requestBody, mapType);

            if (rawData == null) {
                resultMap.put("code", 500);
                resultMap.put("msg", "请求数据为空");
                sendResponse(resp, resultMap);
                return;
            }

            // 验证必要字段
            if (!rawData.containsKey("typeIds")) {
                resultMap.put("code", 500);
                resultMap.put("msg", "缺少分类ID");
                sendResponse(resp, resultMap);
                return;
            }

            // 处理分类ID列表
            Object typeIdsObj = rawData.get("typeIds");
            List<Integer> typeIds = new ArrayList<>();

            if (typeIdsObj instanceof List) {
                List<?> rawList = (List<?>) typeIdsObj;
                for (Object item : rawList) {
                    if (item instanceof Double) {
                        typeIds.add(((Double) item).intValue());
                    } else if (item instanceof Integer) {
                        typeIds.add((Integer) item);
                    } else {
                        typeIds.add(Integer.parseInt(item.toString()));
                    }
                }
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "typeIds字段必须是数组格式");
                sendResponse(resp, resultMap);
                return;
            }

            // 检查ID列表是否为空
            if (typeIds.isEmpty()) {
                resultMap.put("code", 500);
                resultMap.put("msg", "请选择要删除的分类");
                sendResponse(resp, resultMap);
                return;
            }

            // 删除分类
            NewsTypeService newsTypeService = new NewsTypeService();
            int result;


                // 单个删除
                result = newsTypeService.deleteNewsType(typeIds.get(0));


            if (result > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "删除分类成功");
                resultMap.put("deletedCount", result);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "删除分类失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "服务器异常: " + e.getMessage());
        }

        sendResponse(resp, resultMap);
    }

    private void sendResponse(HttpServletResponse resp, Map<String, Object> resultMap) throws IOException {
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}